import {Request,Response,NextFunction} from 'express'
import * as userService from './user.service'
import bcrypt from 'bcrypt'
import _ from 'lodash'

export const validateUserData=async( request:Request,response:Response,next:NextFunction)=>{
    // throw new Error('NAME_IF_REQUIRED'  //  代码级别报错
    // next(new Error('NAME_IS_REQUIRED'))
    console.log('验证用户数据')
    // console.log(request.body)
    const {name,password}=request.body
    if(!name){
        return next(new Error('NAME_IS_REQUIRED'))
    }
    if(!password){
        return next(new Error('PASSWORD_IS_REQUIRED'))
    }

    const user=await userService.getUserByName(name) // model层
    // console.log(user)
    if(user) return next(new Error('USER_ALREADY_EXIST'))
    next()
}

// 什么是中间件
    // 大的问题，交给一系列的中间件来完成
    // 用户生成 POST /users{name:,password}
    // 效验输入
    // 密码加密
    // 数据保存
export const hashPassword=async(request:Request,response:Response,next:NextFunction)=>{
    // console.log('hash')
    const {password} = request.body
    request.body.password=await bcrypt.hash(password,10)
    next()
}

/**
 * 验证更新用户数据
 */
export const validateUpdataUserData = async(request:Request,response:Response,next:NextFunction)=>{
    console.log(request.user,'-----')
    const {validate,update}=request.body
    const {id:userId} = request.user
    // console.log(validate,update)
    try {
        if(!_.has(validate,'password')){
            next(new Error('PASSWORD_IS_REQUIRED'))
        }
        const user = await userService.getUserById(userId,{password:true})
        // console.log(user)
        const matched = await bcrypt.compare(validate.password,user.password)

        if(!matched){
            return next(new Error('PASSWORD_DOSE_NOT_MATCH'))
        }

        if(update.name){
            const user = await userService.getUserByName(update.name)
            if(user){
                return next(new Error('USER_ALREADY_EXIST'));
            }
        }
        // 用户更新密码
        if(update.password){
            const matched = await bcrypt.compare(update.password,user.password);
            if(matched){
                return next(new Error('PASSWORD_IS_THE_SAME'))
            }
        }
        request.body.update.password = await bcrypt.hash(update.password,10);
    } catch (error) {
        next(error)
    }
    next()
}